package awake.stu.dbhb;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Awake
 * Date: 25.02.12
 * Time: 12:31
 * To change this template use File | Settings | File Templates.
 */

public class ImagePanel extends JPanel {

    private BufferedImage originalImage = null;
    private Image image = null;
    public float suSize;

    public ImagePanel() {
        initComponents();
        setBorder(new LineBorder(Color.BLACK));
        setPreferredSize(new Dimension(320, 90));
    }

    private void initComponents() {
        setLayout(null);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

    }

    private void formComponentResized(java.awt.event.ComponentEvent evt) {
        int w = this.getWidth();
        int h = this.getHeight();
        if ((originalImage != null) && (w > 0) && (h > 0)) {
            image = originalImage.getScaledInstance(w, h, Image.SCALE_DEFAULT);
            this.repaint();
        }
    }

    public void paint(Graphics g) {

        if (image != null) {
            g.drawImage(image, 0, 0, null);
        }
        super.paintChildren(g);
        super.paintBorder(g);
    }

    public BufferedImage getImage() {
        return originalImage;
    }

    public void setImage(BufferedImage image) {
        this.originalImage = image;
        suSize = (float) (image.getWidth()) / (float) (image.getHeight());
        formComponentResized(null);
    }

    public void setNewImage(Image im) {
        image = im;
        repaint();
    }

    public void setImageFile(File iF) {
        if (iF == null) {
            originalImage = null;
        } else {
            try {
                BufferedImage bi;
                bi = ImageIO.read(iF);
                originalImage = bi;
            } catch (IOException ex) {
                System.err.println("Неудалось загрузить картинку!");
                ex.printStackTrace();
            }
            formComponentResized(null);
            suSize = (float) (originalImage.getWidth()) / (float) (originalImage.getHeight());
            repaint();
        }
    }
}
